import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:travel/config/map.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/radian.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:travel/screen/flutter_screenutil.dart';

import 'dart:ui' as ui show Image, ImageByteFormat;

class MapController extends GetxController {
  Rx<LatLng> mapCenter = Rx(const LatLng(21.481305, 109.120248));

  Rx<Map<String, Marker>> markers = Rx(<String, Marker>{});

  late Rx<AMapController> mapController;

  late TextEditingController editingController;

  @override
  void onInit() {
    /// 初始化iosKey
    if (GetPlatform.isAndroid || GetPlatform.isIOS || GetPlatform.isFuchsia) {
      AmapSearch.instance.init('iosKey');
    }
    editingController = ToolsUtils.editingController('');
    initDataMaker();
    super.onInit();
  }

  Future<void> initDataMaker() async {
    markers.value.addIf(
        true,
        '21.47-109.13',
        Marker(
            position: const LatLng(21.474414, 109.138469), icon: BitmapDescriptor.defaultMarker));

    ui.Image img = await ToolsUtils.loadImageByProvider(
        const ResizeImage(AssetImage('assets/images/icon/maker2.png'), width: 64, height: 64));
    ByteData? byteData = await img.toByteData(format: ui.ImageByteFormat.png);
    if (byteData != null) {
      markers.value.addIf(
          true,
          '21.49-109.15',
          Marker(
              position: const LatLng(21.461816, 109.128831),
              icon: BitmapDescriptor.fromBytes(byteData.buffer.asUint8List())));
    }

    ByteData bytes = await rootBundle.load('assets/images/icon/map_maker.png');
    markers.value.addIf(
        true,
        '109.132028-21.468765',
        Marker(
          position: const LatLng(
            21.468765,
            109.132028,
          ),
          icon: BitmapDescriptor.fromBytes(bytes.buffer.asUint8List()),
        ));

    ByteData? byteData2 = await ToolsUtils.widgetToImage(
        ToolsUtils.image('icon/maker2.png', width: 64, height: 64, fit: BoxFit.fill));
    if (byteData2 != null) {
      markers.value.addIf(
          true,
          '21.442963-109.122222',
          Marker(
              position: const LatLng(21.48604296323972, 109.16804007692475),
              icon: BitmapDescriptor.fromBytes(byteData2.buffer.asUint8List()),
              infoWindow: const InfoWindow(title: '北海市地图', snippet: '南珠广场')));
    }

    markers.refresh();
  }

  void onMapCreated(AMapController controller) {
    mapController = Rx(controller);
    mapController.refresh();
  }

  Future<void> onSubmitted(String content) async {
    if (GetPlatform.isIOS || GetPlatform.isAndroid || GetPlatform.isFuchsia) {
      List<Poi> lists =
          await AmapSearch.instance.searchKeyword(editingController.text, city: '北海市');
      for (Poi p in lists) {
        markers.value.addIf(
            true,
            p.poiId ?? p.toString(),
            Marker(
                position: LatLng(p.latLng!.latitude, p.latLng!.longitude),
                icon: BitmapDescriptor.fromIconPath('assets/images/icon/maker2.png'),
                // icon: BitmapDescriptor.defaultMarker,
                infoWindow: InfoWindow(title: p.title, snippet: p.address)));
      }
      markers.refresh();
    }
  }

  @override
  void onClose() {
    editingController.dispose();
    mapController.value.disponse();
    super.onClose();
  }

  void addPoiMaker(AMapPoi poi) {
    if (poi.latLng != null) {
      markers.value.addIf(
          true,
          poi.id ?? poi.toString(),
          Marker(
              position: poi.latLng!,
              icon: BitmapDescriptor.fromIconPath('assets/images/icon/maker.png')));
      markers.refresh();
    }
  }

  Future<void> addLatLngMaker(LatLng latLng) async {
    // ByteData bytes = await rootBundle.load('assets/images/icon/map_maker.png');
    // Uint8List list = bytes.buffer.asUint8List();
    // markers.value.addIf(
    //     true, latLng.toString(), Marker(position: latLng, icon: BitmapDescriptor.fromBytes(list)));
    ui.Image img = await ToolsUtils.loadImageByProvider(
        const ResizeImage(AssetImage('assets/images/icon/map_maker2.png'), width: 64, height: 64));
    ByteData? byteData = await img.toByteData(format: ui.ImageByteFormat.png);
    if (byteData != null) {
      markers.value.addIf(
          true,
          latLng.toString(),
          Marker(
              position: latLng, icon: BitmapDescriptor.fromBytes(byteData.buffer.asUint8List())));
    }

    markers.refresh();
  }
}

class MapView extends GetView<MapController> {
  const MapView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: AnnotatedRegion<SystemUiOverlayStyle>(
          value: SystemUiOverlayStyle.dark, child: containerBody(context)),
    );
  }

  Widget containerBody(BuildContext context) {
    return Stack(
      fit: StackFit.expand,
      children: [
        Obx(() => SizedBox(
              height: Get.height,
              width: Get.width,
              child: AMapWidget(
                mapType: MapType.normal,
                apiKey: MapConfig.amapApiKeys,
                privacyStatement: MapConfig.amapPrivacyStatement,
                initialCameraPosition: CameraPosition(target: controller.mapCenter.value, zoom: 15),
                onMapCreated: controller.onMapCreated,
                markers: Set<Marker>.of(controller.markers.value.values),
                onPoiTouched: (AMapPoi poi) {
                  controller.addPoiMaker(poi);
                },
                onTap: (LatLng latLng) {
                  controller.addLatLngMaker(latLng);
                },
              ),
            )),
        Positioned(
            top: Get.mediaQuery.padding.top,
            left: 10,
            right: 10,
            child: Container(
              height: 50,
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  boxShadow: [
                    BoxShadow(
                        offset: Offset.zero,
                        blurRadius: 5.0,
                        spreadRadius: 0.0,
                        color: ColorsUtils.rgba(0, 0, 0, 0.247058823529412))
                  ]),
              alignment: Alignment.centerLeft,
              child: SizedBox(
                height: 35,
                child: Row(
                  children: [
                    Container(
                      width: 40,
                      alignment: Alignment.center,
                      child: IconButton(
                        onPressed: Get.back,
                        icon: Icon(
                          Icons.arrow_back_ios,
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                          size: 20,
                        ),
                      ),
                    ),
                    Expanded(
                        child: Container(
                      padding: const EdgeInsets.only(right: 15),
                      child: Row(
                        children: [
                          Container(
                            width: 65,
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                              gradient: LinearGradient(colors: [
                                ColorsUtils.rgba(52, 120, 246, 1),
                                ColorsUtils.rgba(2, 167, 240, 1)
                              ], stops: const [
                                0,
                                0.99
                              ], transform: GradientRotation(RadianUtils.angleToRadian(90))),
                              borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(18), bottomLeft: Radius.circular(18)),
                            ),
                            child: Text.rich(TextSpan(children: [
                              TextSpan(
                                  text: '北海', style: StylesUtils.customTextStyle(fontSize: 13.sp)),
                              const WidgetSpan(
                                  child: Icon(Icons.arrow_drop_down_outlined,
                                      color: Colors.white, size: 15),
                                  alignment: PlaceholderAlignment.middle)
                            ])),
                          ),
                          Expanded(
                              child: Container(
                            decoration: BoxDecoration(
                                color: ColorsUtils.rgba(245, 245, 245, 1),
                                borderRadius: const BorderRadius.only(
                                    topRight: Radius.circular(18),
                                    bottomRight: Radius.circular(18))),
                            child: Row(
                              children: [
                                Expanded(
                                    child: TextField(
                                  controller: controller.editingController,
                                  cursorWidth: 2.0,
                                  cursorRadius: const Radius.circular(2),
                                  cursorColor:
                                      ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                                  style: StylesUtils.customTextStyle(
                                      fontSize: 15.sp, color: ColorsUtils.color3333),
                                  decoration: InputDecoration(
                                    prefixIcon: Icon(Icons.search_sharp, size: 25.sp),
                                    prefixIconColor: Colors.black54,
                                    prefixIconConstraints: BoxConstraints.expand(width: 35.w),
                                    border: InputBorder.none,
                                    focusedBorder: InputBorder.none,
                                    hintText: '搜索目的地/景点',
                                    contentPadding: const EdgeInsets.symmetric(vertical: 10),
                                    isCollapsed: true,
                                    isDense: true,
                                    hintStyle: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color9999,
                                    ),
                                  ),
                                  onSubmitted: controller.onSubmitted,
                                )),
                                InkWell(
                                  onTap: () {
                                    controller.editingController.text = '';
                                  },
                                  child: Center(
                                    child: SizedBox(
                                      width: 18,
                                      height: 18,
                                      child: CustomPaint(
                                        painter: _ClosedIcon(),
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          )),
                          InkWell(
                            onTap: () {
                              controller.onSubmitted('');
                            },
                            child: Container(
                                width: 50,
                                alignment: Alignment.centerRight,
                                child: Text(
                                  '搜索',
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color3333, fontSize: 15.sp),
                                )),
                          )
                        ],
                      ),
                    ))
                  ],
                ),
              ),
            )),
        Positioned(
            width: 145,
            height: 35,
            top: Get.mediaQuery.padding.top + 60,
            left: 10,
            child: Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.symmetric(horizontal: 5),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  boxShadow: [
                    BoxShadow(
                        color: ColorsUtils.rgba(0, 0, 0, 0.247058823529412),
                        offset: Offset.zero,
                        blurRadius: 5.0,
                        spreadRadius: 0.0)
                  ]),
              child: Wrap(
                spacing: 4,
                children: [
                  ToolsUtils.assetImageSvg('u1340.svg', width: 15, height: 10),
                  Text(
                    '景点：4分以上',
                    style:
                        StylesUtils.customTextStyle(color: ColorsUtils.color3333, fontSize: 13.sp),
                  ),
                  Icon(
                    Icons.arrow_drop_down_rounded,
                    size: 15,
                    color: ColorsUtils.parseColorFromHexString(ColorsUtils.color6666),
                  )
                ],
              ),
            )),
        Positioned(
            width: 70,
            height: 35,
            top: Get.mediaQuery.padding.top + 60,
            left: 165,
            child: Container(
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(5),
                  boxShadow: [
                    BoxShadow(
                        color: ColorsUtils.rgba(0, 0, 0, 0.247058823529412),
                        offset: Offset.zero,
                        blurRadius: 5.0,
                        spreadRadius: 0.0)
                  ]),
              child: Wrap(
                spacing: 5,
                children: [
                  ToolsUtils.assetImageSvg('u1343.svg', width: 13, height: 15),
                  Text(
                    '酒店',
                    style:
                        StylesUtils.customTextStyle(color: ColorsUtils.color3333, fontSize: 13.sp),
                  )
                ],
              ),
            ))
      ],
    );
  }
}

class _ClosedIcon extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint()
      ..style = PaintingStyle.fill
      ..isAntiAlias = true
      ..color = ColorsUtils.parseColorFromHexString(ColorsUtils.colorCccc);
    canvas.drawCircle(Offset(size.width / 2, size.height / 2), size.height / 2, paint);
    paint.color = Colors.white;
    paint.strokeWidth = 2.5;
    paint.style = PaintingStyle.stroke;

    canvas.drawLine(Offset(size.width / 4, size.height / 4),
        Offset(size.width * 3 / 4, size.height * 3 / 4), paint);

    canvas.drawLine(Offset(size.width / 4, size.height * 3 / 4),
        Offset(size.width * 3 / 4, size.height / 4), paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}
